package com.bto.solar.work.service;

import com.alibaba.fastjson2.JSONObject;
import com.bto.solar.work.constant.BizOperateLogEnum;
import com.bto.solar.work.constant.BizStageEnum;
import com.bto.solar.work.constant.BizTaskEnum;
import com.bto.solar.work.constant.BizTaskStateEnum;
import com.bto.solar.work.constant.Constants;
import com.bto.solar.work.constant.DBConstants;
import com.bto.solar.work.dao.IOrderOperationLogService;
import com.bto.solar.work.dto.ApprovalReq;
import com.bto.solar.work.dto.order.OrderLogReq;
import com.bto.solar.work.entity.Appoint;
import com.bto.solar.work.entity.OrderOperationLog;
import com.bto.solar.work.entity.User;
import com.bto.solar.work.utils.NullUtils;
import com.bto.solar.work.utils.StringUtils;
import com.bto.solar.work.vo.OperateLogVo;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 王小波
 * @description:
 * @date 2023/8/14 15:28
 */

@Component
public class BtoOrderOperateLogService {
    @Autowired
    private IOrderOperationLogService orderOperationLogService;
    @Autowired
    private BtoUserService btoUserService;



    /**
     * 查询订单操作记录
     */
    public PageInfo<OperateLogVo> getOrderOperateLog(Integer pageNum , Integer pageSize , OrderLogReq orderLogReq){
        String orderId = orderLogReq.getOrderId();
        List<OperateLogVo> operateLogVoList = buildOrderOperateLogVo(getOrderLogByOrderIdAndStateTag(orderId , null , null , null ));
        int start = (pageNum - 1) * pageSize;
        int end = Math.min(pageNum * pageSize, operateLogVoList.size());
        List<OperateLogVo> operateLogVoSubList = operateLogVoList.subList(start, end);
        PageInfo<OperateLogVo> pageInfo = new PageInfo<>(operateLogVoSubList);
        pageInfo.setTotal(operateLogVoList.size());
        return pageInfo;
    }


    /**
     * 查询各任务的审批记录
     */
    public List<OrderOperationLog> getOrderApprovalLog(OrderLogReq orderLogReq){
        String orderId = orderLogReq.getOrderId();
        return getOrderLogByOrderIdAndStateTag(orderId, orderLogReq.getStageId(), orderLogReq.getTaskId(), Constants.APPROVAL);
    }


    public List<OrderOperationLog> getOrderLogByOrderIdAndStateTag(String orderId, String stageId, String taskId, String stageTag) {
        return orderOperationLogService.lambdaQuery()
                .eq(OrderOperationLog::getOrderId, orderId)
                .eq(StringUtils.isNotEmpty(stageId), OrderOperationLog::getStageId, stageId)
                .eq(StringUtils.isNotEmpty(taskId), OrderOperationLog::getTaskId, taskId)
                .like(StringUtils.isNotEmpty(stageTag), OrderOperationLog::getStateId, stageTag)
                .orderByDesc(OrderOperationLog::getCreateTime)
                .list();
    }
    public List<OrderOperationLog> getOrderLog(String orderId ,String stageId , String taskId ,  String stateId){
        return orderOperationLogService.lambdaQuery()
                .eq(OrderOperationLog::getOrderId , orderId)
                .eq(StringUtils.isNotEmpty(stageId) ,  OrderOperationLog::getStageId , stageId)
                .eq(StringUtils.isNotEmpty(taskId) , OrderOperationLog::getTaskId , taskId)
                .eq(StringUtils.isNotEmpty(stateId) , OrderOperationLog::getStateId , stateId)
                .orderByDesc(OrderOperationLog::getCreateTime)
                .list();
    }

    /**
     * 构建前端订单操作记录视图
     */
    private List<OperateLogVo> buildOrderOperateLogVo(List<OrderOperationLog> orderOperationLogs){
        HashMap<String ,String> viewMap = new HashMap<>();
        viewMap.put(DBConstants.OPT_NEW , "创建");
        viewMap.put(DBConstants.OPT_UPDATE , "更新");
        viewMap.put(BizTaskStateEnum.WAITING_FILLED.getStateId()  , "填写");
        viewMap.put(BizTaskStateEnum.WAITING_SIGN.getStateId()  , "等待签约");
        viewMap.put(BizTaskStateEnum.FILLED_OK.getStateId()  , "填写完毕");
        viewMap.put(BizTaskStateEnum.WAITING_APPOINT.getStateId(), "等待指派");
        viewMap.put(BizTaskStateEnum.WAITING_APPROVAL_INNER.getStateId()  , "提交内审");
        viewMap.put(BizTaskStateEnum.WAITING_APPROVAL_BTO.getStateId()  , "提交总部审核");
        viewMap.put(BizTaskStateEnum.WAITING_APPROVAL_LEASE.getStateId()  , "提交资方审核");
        viewMap.put(BizTaskStateEnum.APPROVAL_PASS.getStateId()  , "内审通过");
        viewMap.put(BizTaskStateEnum.APPROVAL_PASS_BTO.getStateId()  , "总部审核通过");
        viewMap.put(BizTaskStateEnum.APPROVAL_PASS_LEASE.getStateId()  , "审核通过");
        viewMap.put(BizTaskStateEnum.APPROVAL_REJECT.getStateId()  , "内审拒绝");
        viewMap.put(BizTaskStateEnum.APPROVAL_REJECT_BTO.getStateId()  , "总部审核拒绝");
        viewMap.put(BizTaskStateEnum.APPROVAL_REJECT_LEASE.getStateId()  , "审核拒绝");
        viewMap.put(BizTaskStateEnum.WAITING_SIGN_RE.getStateId(), "等待重新签约");
        viewMap.put(BizTaskStateEnum.TERMINATE.getStateId(), "终止");
        viewMap.put(BizTaskStateEnum.SIGNED.getStateId()  , "完成签约");

        List<OperateLogVo> operateLogVoList = new ArrayList<>();

        for (OrderOperationLog log : orderOperationLogs) {
            OperateLogVo operateLogVo = new OperateLogVo();

            String stageId = log.getStageId();
            String taskId = log.getTaskId();
            String optType = log.getType();
            long sort = log.getCreateTime().getTime();



            String stageName = BizStageEnum.valueOf(stageId).getStageName();
            String taskName = StringUtils.isEmpty(taskId) ? stageName : BizTaskEnum.valueOf(taskId).getTaskName();
            String optName = viewMap.getOrDefault(optType , "操作");

            Long operatorId = log.getOperatUser();
            String operator = "";
            if(NullUtils.isNotNull(operatorId) && 0L != operatorId){
                User userByUserId = btoUserService.getUserByUserId(operatorId);
                if(NullUtils.isNotNull(userByUserId)){
                    operator = userByUserId.getName();
                }
            }
            else if(optType.contains(Constants.LEASE) || optType.contains(Constants.TERMINATE)){
                operator = "资方";
            }


            if (DBConstants.OPT_NEW.equals(optType)) {
                optName = BizOperateLogEnum.OPT_NEW.getOperateName();
                taskName = taskName +  "信息，ID 为 " + log.getOrderId();
                sort = sort + BizOperateLogEnum.OPT_NEW.getSort();
            }
            else if (DBConstants.OPT_UPDATE.equals(optType)) {
                continue;
            } else if (BizTaskStateEnum.WAITING_FILLED.getStateId().equals(optType) && BizTaskStateEnum.WAITING_FILLED.getStateId().equals(log.getType())) {
                if (BizTaskEnum.TASK_JSKC.getTaskId().equals(taskId)) {
                    Appoint appoint = JSONObject.parseObject(log.getOperatInfo(), Appoint.class);
                    if (NullUtils.isNotNull(appoint)) {
                        if (NullUtils.isNotNull(appoint.getUserId())) {
                            User apointUser = btoUserService.getUserByUserId(appoint.getUserId());
                            optName = "已指派" + apointUser.getName();
                        }
                    }
                } else {
                    operator = "系统";
                    optName = BizOperateLogEnum.OPT_OPPEN.getOperateName();
                    sort = sort + BizOperateLogEnum.OPT_OPPEN.getSort();
                    if (BizTaskEnum.TASK_YSXX.getTaskId().equals(taskId)) {
                        sort = BizOperateLogEnum.OPT_OPPEN.getSort();
                    }
                }
            } else if (BizTaskStateEnum.WAITING_APPOINT.getStateId().equals(optType)) {
                operator = "";
                optName = "技术勘察员" + optName;
            }
            else {
                sort = sort + BizOperateLogEnum.OPT_OTHER.getSort();
            }


            String title = stageName + "阶段, " + operator + optName + "，" + taskName;

            if(optType.contains(Constants.REJECT) || optType.contains(Constants.PASS) || optType.contains(Constants.TERMINATE)) {
                ApprovalReq approvalReq = JSONObject.parseObject(log.getApprovalInfo(), ApprovalReq.class);
                if (NullUtils.isNotNull(approvalReq)) {
                    operateLogVo.setReason(approvalReq.getRejectReason());
                    operateLogVo.setApprovalReq(approvalReq);
                }
            }
            operateLogVo.setTitle(title);
            operateLogVo.setTime(log.getCreateTime());
            operateLogVo.setOperator(operator);
            operateLogVo.setSort(sort);
            operateLogVoList.add(operateLogVo);
        }
        return operateLogVoList.stream().sorted(Comparator.comparing(OperateLogVo::getSort).reversed()).collect(Collectors.toList());
    }
}
